#include <REGX52.H>
#include <INTRINS.H>
#include "LCD1602.h"
#include "Delay.h"
#include "DS18B20.h"
#include "Key.h"
#include "AT24C02.h"
#include "Timer0.h"

char T_High = 28;	//带符号char类型
char T_Low = 19;	//带符号char类型

void main()
{
	int T;
	int temT;
	float temper;
	unsigned char KeyNum = 0;
	unsigned char flashFlag = 0;
	
	LCD_Init();
	LCD_ShowString(1,1,"T:");
	
	Timer0_Init();		//定时器Timer0初始化
	
	
	T_High = AT24c02_ReadByte(0);
	T_Low =  AT24c02_ReadByte(1);
	
	//第一次读取判断AT24C02 E2PROM中值是否合法
	if(T_High > 125 || T_Low < -55 || T_High < T_Low){
		T_High = 28;
		T_Low = 19;
	}
	
	while(1)
	{
		/* 温度读取及显示 */
		DS18B20_ConvertT();				//DS18B20采集温度
		Delay(1);						//延时1ms，等待温度转换完成
		T = DS18B20_ReadT();			//DS18B20读取问题
		
		if(T < 0)				
		{
			LCD_ShowChar(1,3,'-');		//如果温度小于0，显示'-'号
			temT=-T;						//将温度变为正数
		}
		else						
		{
			LCD_ShowChar(1,3,'+');		//显示正号
			temT = T;
		}
		LCD_ShowNum(1,4,temT/16,3);		//显示温度整数部分
		LCD_ShowChar(1,7,'.');			//显示小数点
		LCD_ShowNum(1,8,((unsigned long)temT)*100/16%100,2);	//显示温度小数部分
		
		
		/* 阈值判断及显示 */
		LCD_ShowString(2,1,"H:");
		LCD_ShowNum(2,3,T_High,2);
		LCD_ShowString(2,5," L:");
		LCD_ShowNum(2,8,T_Low,2);
		
		
		//判断温度过高告警，和温度过低告警
		temper = T/16.0;
		if(temper > T_High)
		{
			//flashFlag != flashFlag;
			//if(flashFlag)
				LCD_ShowString(2, 11, "HO");	//告警信息闪烁
			//else
			//	LCD_ShowString(2, 11, "  ");
		}
		else if(temper < T_Low)
		{
			//flashFlag != flashFlag;
			//if(flashFlag)
				LCD_ShowString(2, 11, "LO");	//告警信息闪烁
			//else
			//	LCD_ShowString(2, 11, "  ");
		}
		else
		{
			LCD_ShowString(2, 11, "  ");
		}
		
		
		//独立按键部分，
		//KEY1增加温度高门限值
		//KEY2降低温度高门限值
		//KEY3增加温度低门限值
		//KEY4降低温度低门限值
		KeyNum = Key();
		if(KeyNum)
		{
			if(KeyNum == 1)
			{
				T_High++;
			}
			else if(KeyNum == 2)
			{
				T_High--;
				if(T_High <= T_Low)
					T_High = T_Low + 1;
			}
			else if(KeyNum == 3)
			{
				T_Low++;
				if(T_Low >= T_High)
					T_Low = T_High - 1;
			}
			else if(KeyNum == 4)
			{
				T_Low--;
			}
			
			/* 温度阈值存到AT24C02 E2PROM */
			AT24c02_WriteByte(0, T_High);
			Delay(5);
			AT24c02_WriteByte(1, T_Low);
			Delay(5);
		}
	}
}

/**
  * @brief  定时器0中断处理函数模版
  * @param  无
  * @retval 无
  */
void Timer0_Routine(void) interrupt 1
{
	static unsigned int count = 0;
	
	count++;

	if(count >= 20)		//定时器T0每1ms中断一次，每20ms扫描一次独立按键是否按下或松开
	{
		Key_Loop();
		count = 0;
	}
	
	//定时器溢出之后需要重新装载
	TH0 = (65535 - 1000) / 256;					//12MHz晶振，12分频
	TL0 = (65535 - 1000) % 256 + 1; 			//
}
